$(function () {
    //手机端不连接
    // if ($(window).width() > 768) {
    console.log('正在连接打印机');
    connection();
    // }
});
var ws;
var wsUrl = 'ws://127.0.0.1:2012';

function connection() {
    if (is_remote_print) {
        //远程打印
        wsUrl = 'ws://' + pass_remote_ip + ':2012';
    }

    if ('WebSocket' in window) {
        ws = new WebSocket(wsUrl);
    } else if ('MozWebSocket' in window) {
        ws = new MozWebSocket(wsUrl);
    } else {
        alert('当前浏览器不支持');
    }

    //注册各类回调
    ws.onopen = function () {
        console.log('连接打印后台成功');
    }

    ws.onclose = function () {
        // alert('与打印后台断开连接');
    }
    ws.onerror = function () {
        // alert('数据传输发生错误');
        layer.msg('打印服务未开启', {time: 4000});
    }
    ws.onmessage = function (receiveMsg) {
        if (receiveMsg.data.split("|")[0] == "B_GetPrinterStatus") {

            var ret = receiveMsg.data.split("|")[1];
            if (ret == 2) {
                document.getElementById("status").value = "2:USB端口开启失败";
                return;
            } else if (ret == 7) {
                document.getElementById("status").value = "7:纸张/碳带用完！";
                return;
            } else if (ret == 4) {
                document.getElementById("status").value = "4:内存溢出！";          //4:内存溢出！
                return;
            } else if (ret == 4) {
                document.getElementById("status").value = "4 碳带用完或安装错误！";                       //碳带用完或安装错误！";
                return;
            } else if (ret == 3) {
                document.getElementById("status").value = "3:条码格式错误！";           //3:条码格式错误！";
                return;
            } else if (ret == 1) {
                document.getElementById("status").value = "1:打印命令错误！";                 //1:打印命令错误！
                return;
            } else if (ret == 6) {
                document.getElementById("status").value = "6:串口通信异常！";                 //6:串口通信异常！
                return;
            } else if (ret == 50) {
                document.getElementById("status").value = "50:打印机忙碌！";                 //50:打印机忙碌！
                return;
            } else if (ret == 12) {
                document.getElementById("status").value = "12:打印机暂停！";                 //12:打印机暂停
                return;
            } else if (ret == 9) {
                document.getElementById("status").value = "9:未取得返回值";                 //9:未取得返回值
                return;
            } else if (ret == 0) {
                document.getElementById("status").value = "0:等待列印!";                 //0:等待列印!
                return;
            }

        }
    }
}

function getStatus() {
    ws.send('B_EnumUSB');
    ws.send('B_CreateUSBPort|1');
    ws.send('B_GetPrinterStatus');

    ws.send('B_ClosePrn');
}

function print_passedCard(obj) {
    var tr = $(obj).closest("tr"),
        id = tr.find("td.res_id input:checkbox").val(),
        tester_names = "";//检验人员
    //############## 检验人员 start ###########################
    if (is_tester_code) {
        //代号
        tester_names = tr.find("td.tester_codes").text();
    } else {
        //真实姓名
        tester_names = tr.find("td.tester_names").text();
    }
    if(tester_count == 0){
        tester_names = tester_names.replace(/，/g,' ');
    }else{
        var name_arrs = tester_names.split('，'),
            name_arr = [];//字符串转数组
        $.each(name_arrs,function (i) {
            let name = name_arrs[i];
            if (name !== '') {
                name_arr.push(name);
            }
        })
        let name_arr_len = name_arr.length;
        if (tester_count == 2 && name_arr_len > 1) {
            //合格证上的检测人员填写 2 个人
            tester_names = name_arr[0] + ' ' + name_arr[1];//合格证上只保留两个检验人员
        } else {
            //合格证上的检测人员填写 1 个人
            tester_names = name_arr[0];//合格证上只保留一个检验人员
        }
    }
    // console.log(tester_names);
    tester_names = tester_names === undefined ? '' : tester_names;
    var voltage = tr.find("td.voltage").text();
    if (voltage == "/" || voltage == "\\" || voltage == "无") {
        voltage = "";
    }
    //############## 检验人员 end ###########################

    var guige_xinghao = tr.find("td.guige_xinghao").text();
    if (guige_xinghao == "/" || guige_xinghao == "\\" || guige_xinghao == "无") {
        guige_xinghao = "";
    }

    if (voltage == "" && guige_xinghao == "") {
        voltage_guige_xinghao = "/";
    } else if (voltage != "" && guige_xinghao != "") {
        voltage_guige_xinghao = voltage + "/" + guige_xinghao;
    } else {
        voltage_guige_xinghao = voltage + guige_xinghao;
    }
    var data = [getData(tr, id, tester_names)];
    printCode(data);
}

/* 批量打印合格证 */
function batch_print_passedCard(toImg=0) {
    if (ws.readyState !== 1 && toImg == 0) {
        layer.msg('打印服务未开启！');
        return;
    }
    var doms = $("tbody tr > td:first-child input:checkbox:checked"), l = doms.length;
    if (l == 0) {
        layer.msg('请先勾选一条记录', {time: 2000});
        return;
    }

    var nodoms = $("tbody tr > td:first-child input:checkbox:checked.no-hege"), nol = nodoms.length, index = 0;
    if (nol > 0) {
        //询问框
        index = layer.confirm('打印不合格证吗？', {
            btn: ['打印', '不打印'] //按钮
        }, function () {
            layer.close(index);
            print1(doms,toImg);
        }, function () {
            doms = $("tbody tr > td:first-child input:checkbox:checked.hege");
            print1(doms,toImg);
        });
    } else {
        print1(doms,toImg);
    }
}

function print1(doms,toImg) {
    let l = doms.length,msg= '将为您打印 ' + l + ' 条记录，<br>确定要批量打印合格证吗？';
    if (toImg == 1){
        msg= '将为您输出 ' + l + ' 条记录，<br>确定要批量输出合格证图片吗？'
    }
    layer.confirm(msg, {title: '询问', icon: 3}, function (index) {
        layer.close(index);
        var data = [];
        doms.each(function () {
            var tr = $(this).closest("tr");
            var id = $(this).val();

            var tester_names = "";//检验人员
            if (is_tester_code) {
                //代号
                tester_names = tr.find("td.tester_codes").text();
            } else {
                //真实姓名
                tester_names = tr.find("td.tester_names").text();
            }

            var name_arr = tester_names.split('，');//字符串转数组
            if (tester_count == 2) {
                //合格证上的检测人员填写 2 个人
                tester_names = name_arr[0] + ' ' + name_arr[1];//合格证上只保留两个检验人员
            } else {
                //合格证上的检测人员填写 1 个人
                tester_names = name_arr[0];//合格证上只保留一个检验人员
            }

            var voltage = tr.find("td.voltage").text();
            if (voltage == "/" || voltage == "\\" || voltage == "无") {
                voltage = "";
            }

            var guige_xinghao = tr.find("td.guige_xinghao").text();
            if (guige_xinghao == "/" || guige_xinghao == "\\" || guige_xinghao == "无") {
                guige_xinghao = "";
            }

            if (voltage == "" && guige_xinghao == "") {
                voltage_guige_xinghao = "/";
            } else if (voltage != "" && guige_xinghao != "") {
                voltage_guige_xinghao = voltage + "/" + guige_xinghao;
            } else {
                voltage_guige_xinghao = voltage + guige_xinghao;
            }
            if (data[tr.find("td.bar_code").text()] !== undefined) {
                layer.msg('数据部分解析失败，正在为您打印失败之前的数据！');
                return false;
            }
            data[tr.find("td.bar_code").text()] = getData(tr, id, tester_names);
        });
        if(toImg == 1){
            printCodeImg(data);
        }else{
            printCode(data);
        }
    });
}

function getData(tr, id, tester_names) {
    let res = tr.find("td.res").text();
    try{
        res = print_ahead == 1 ? '合格' : res;
    }catch(err){
        console.log(err);
    }
    return {
        url: 'http://' + location.host + '/viewRes?id=' + id + '&k=' + tr.find("td.bar_code span").data("key"),
        bar_code: tr.find("td.bar_code").text(),
        tool_name: tr.find("td.tool_name").text(),
        class_name: tr.find("td.class_name").text(),
        gqj_ID: tr.find("td.gqj_ID").text(),
        third_id: tr.find("td.third_id").text(),
        guige_xinghao: voltage_guige_xinghao,
        self_num: tr.find("td.self_num").text(),
        test_time: tr.find("td.test_time").text(),
        next_time: tr.find("td.next_time").text(),
        class: tr.find("td.class").text(),
        std_num: tr.find("td.std_num").text(),
        voltage: tr.find("td.voltage").text(),
        guige_xinghao_pure: tr.find("td.guige_xinghao").text(),
        res: res,
        tester_names: tester_names
    };
}

function printCode(data) {
    print_style = parseInt(print_style);
    // console.log(data);
    switch (print_style) {
        case 1:
            print(data);
            break;
        case 2:
            print2(data);
            break;
        case 3:
            print3(data);
            break;
        default:
            print(data);
            break;
    }
}
function printCodeImg(data) {
    // $('#card-img').removeClass('hidden');
    for (i in data){
        let info = data[i],x=y=10,width = 210,nameLen = company_name.length, nameX=(width-60-nameLen)/2;
        console.log(info)
        new QRCode('qrcode',{
            width: 50,
            height: 50
        }).makeCode(info.gqj_ID);
        var c=document.getElementById("canvas"),cxt = c.getContext("2d");
        cxt.fillStyle="#ffffff";  //背景色
        cxt.fillRect(0,0,1000,1000);
        cxt.fillStyle = "#000000";  //文字颜色
        cxt.drawImage($('#qrcode').find('canvas')[0],x,y);  //左上角
        cxt.font = "bold 12px 黑体";
        y += 20;cxt.fillText(company_name,nameX,y);
        cxt.font = "normal 24px 黑体";
        y += 30; cxt.fillText(info.res === '不合格' ?  '不 合 格 证' :  '合 格 证',x+80,y);
        cxt.font = "normal 12px 黑体";
        y += 20; cxt.fillText("试样名称："+info.tool_name,x,y);
        y += 18; cxt.fillText("规格型号："+info.guige_xinghao,x,y);
        y += 18; cxt.fillText("试验编号："+info.bar_code,x,y);
        y += 18; cxt.fillText("自 编 号："+info.self_num,x,y);
        y += 18; cxt.fillText("试验日期："+info.test_time,x,y);
        y += 18; cxt.fillText("有效期至："+info.next_time,x,y);
        y += 18; cxt.fillText("试验人员："+info.tester_names,x,y);
        cxt.drawImage($('#qrcode').find('canvas')[0],width,y-50);  //右下角
        downloadIamge(c.toDataURL(),info.bar_code)
    }
}

function PassedCardtoImg(options){
    var settings = {
        canvas:document.getElementsByTagName("canvas")[0], //canvas对象，必填，不填写默认找到页面中的第一个canvas
        canvasWidth:480, //canvas的宽度
        drawStartX:10, //绘制字符串起始x坐标
        drawStartY:30, //绘制字符串起始y坐标
        lineHeight:30, //文字的行高
        font:"24px 'Microsoft Yahei'", //文字样式
        text:"请修改掉默认的配置", //需要绘制的文本
        drawWidth:460, //文字显示的宽度
        color:"#000000", //文字的颜色
        backgroundColor:"#ffffff", //背景颜色
    };

    //将传入的配置覆盖掉默认配置
    if(!!options && typeof options === "object"){
        for(var i in options){
            settings[i] = options[i];
        }
    }

    //获取2d的上线文开始设置相关属性
    var canvas = settings.canvas;
    canvas.width = settings.canvasWidth;
    var ctx = canvas.getContext("2d");

    //绘制背景色
    ctx.fillStyle = settings.backgroundColor;
    ctx.fillRect(0,0,canvas.width,canvas.height);

    //绘制文字
    ctx.font = settings.font;
    ctx.fillStyle = settings.color;
    var lineWidth = 0; //当前行的绘制的宽度
    var lastTextIndex = 0; //已经绘制上canvas最后的一个字符的下标
    //由于改变canvas 的高度会导致绘制的纹理被清空，所以，不预先绘制，先放入到一个数组当中
    var arr = [];
    for(var i = 0; i<settings.text.length; i++){
        //获取当前的截取的字符串的宽度
        lineWidth = ctx.measureText(settings.text.substr(lastTextIndex,i-lastTextIndex)).width;

        if(lineWidth > settings.drawWidth){
            //判断最后一位是否是标点符号
            if(judgePunctuationMarks(settings.text[i-1])){
                arr.push(settings.text.substr(lastTextIndex,i-lastTextIndex));
                lastTextIndex = i;
            }else{
                arr.push(settings.text.substr(lastTextIndex,i-lastTextIndex-1));
                lastTextIndex = i-1;
            }
        }
        //将最后多余的一部分添加到数组
        if(i === settings.text.length - 1){
            arr.push(settings.text.substr(lastTextIndex,i-lastTextIndex+1));
        }
    }

    //根据arr的长度设置canvas的高度
    canvas.height = arr.length*settings.lineHeight+settings.drawStartY;

    ctx.font = settings.font;
    ctx.fillStyle = settings.color;
    for(var i =0; i<arr.length; i++){
        ctx.fillText(arr[i],settings.drawStartX,settings.drawStartY+i*settings.lineHeight);
    }

    //判断是否是需要避开的标签符号
    function judgePunctuationMarks(value) {
        var arr = [".",",",";","?","!",":","\"","，","。","？","！","；","：","、"];
        for(var i = 0; i< arr.length; i++){
            if(value === arr[i]){
                return true;
            }
        }
        return false;
    }
    return canvas.toDataURL();
}
